package com.shangyueshang.controller.sys;

import com.shangyueshang.model.SysRole;
import com.shangyueshang.model.SysRoleMenu;
import com.shangyueshang.request.IdDTO;
import com.shangyueshang.request.PageReq;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.service.SysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/5 18:51
 * @version: v1.0.0
 */
@RestController
@RequestMapping("/role")
public class SysRoleController {
	
	@Resource
	private SysRoleService sysRoleService;
	
	/**
	 * 保存角色
	 *
	 * @param sysRole
	 * @return
	 */
	@PostMapping("/save")
	@PreAuthorize("hasAuthority('sys:role:add') and hasAuthority('sys:role:edit')")
	public HttpResult save(@Valid @RequestBody SysRole sysRole) {
		return sysRoleService.create(sysRole);
	}
	
	/**
	 * 删除角色
	 *
	 * @param ids
	 * @return
	 */
	@PostMapping("/delete")
	@PreAuthorize("hasAuthority('sys:role:delete')")
	public HttpResult delete(@Size(min = 1, message = "请传入角色ID") @RequestBody List<IdDTO> ids) {
		sysRoleService.removeByIds(ids.stream().map(IdDTO::getId).collect(Collectors.toList()));
		return HttpResult.ok();
	}
	
	/**
	 * 分页查询
	 *
	 * @param pageReq
	 * @return
	 */
	@PostMapping("/findPage")
//	@PreAuthorize("hasAuthority('sys:role:view')")
	public HttpResult findPage(@RequestBody PageReq pageReq) {
		return HttpResult.ok(sysRoleService.findPage(pageReq));
	}
	
	/**
	 * 查询全部角色
	 *
	 * @return
	 */
	@GetMapping("/findAll")
//	@PreAuthorize("hasAuthority('sys:role:view')")
	public HttpResult findAll() {
		List<SysRole> list = sysRoleService.list();
		list.sort(Comparator.comparing(SysRole::getCreateTime).reversed());
		return HttpResult.ok(list);
	}
	
	/**
	 * 保存角色菜单
	 *
	 * @param roleMenus
	 * @return
	 */
	@PostMapping("/saveRoleMenus")
	@PreAuthorize("hasAuthority('sys:role:add')")
	public HttpResult saveRoleMenus(@Size(min = 1, message = "请传入角色菜单数据") @RequestBody List<SysRoleMenu> roleMenus) {
		return sysRoleService.saveRoleMenus(roleMenus);
	}
	
	/**
	 * 查询角色菜单
	 *
	 * @param roleId
	 * @return
	 */
	@GetMapping("/findRoleMenus")
	@PreAuthorize("hasAuthority('sys:role:view')")
	public HttpResult findRoleMenus(@NotNull @RequestParam Long roleId) {
		return HttpResult.ok(sysRoleService.findRoleMenus(roleId));
	}
}
